﻿<template>
    <div class="hidden h100 flex-column">
        <component is="style" />
            <div class="flex-row padding-tb-8">
                <el-form :inline="true" :model="query" size="small" class="demo-form-inline margin-left-8 flex-row-fill">
                    <el-form-item label="时间">
                        <el-date-picker v-model="date" type="daterange" range-separator="至" start-placeholder="开始日期"
                                        end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :editable="false"
                                        :unlink-panels="true" :picker-options="pickerOptions" :clearable="false"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="品牌">
                        <el-select v-model="query.bId" placeholder="请选择品牌" v-on:visible-change="visibleChange(1)" clearable>
                            <el-option v-for="(item,index) in eoModelList" :label="item.text" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="适用车型">
                        <el-select v-model="query.eoApplications" placeholder="请选择适用车型" v-on:visible-change="visibleChange(2)"
                                   clearable>
                            <el-option v-for="(item,index) in carList" :label="item.cName" :value="item.cName"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" v-on:click="loadList">查询</el-button>
                        <el-button type="primary" v-on:click="add(0)" icon="el-icon-plus" plain>新增</el-button>
                        <el-button class="margin-left-10" type="primary" size="small" icon="fa fa-file-excel-o"
                                   v-on:click="exportEcel">导出</el-button>
                    </el-form-item>
                </el-form>
                <el-pagination background v-on:size-change="pagerSizeChange" v-on:current-change="pagerIndexChange"
                               :current-page="query.pageIndex" :page-sizes="[15,30,50,100]" :page-size="query.pageSize"
                               layout="prev, pager, next, total, jumper, sizes" :total="query.rowCount" :small="true"></el-pagination>
            </div>
            <div class="flex-column-fill hidden">
                <vxe-table :data="tableData" ref="vxeTable" stripe border style="width:100%;" height="100%" size="small" auto-resize :row-config="{isCurrent: true, isHover: true}" :column-config="{minWidth:'60px'}" show-header-overflow show-overflow :footer-method="footerMethod" show-footer>
                    <vxe-column field="time" min-width="150" align="center" fixed="left" title="售出时间">
                        <template #default="d">
                            <span>{{d.row.time}}</span>
                        </template>
                    </vxe-column>
                    <vxe-column min-width="250" align="center" show-overflow-tooltip>
                        <template #header="d">
                            <div class="flex-row" style="justify-content: center;">
                                <!-- <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" circle
                    v-on:click="add()"></el-button> -->
                                <span class="margin-left-6 margin-right-6">机油品牌/型号</span>
                                <!-- <el-input style="width:150px; margin-right:4px;" placeholder="检索" size="small"
                    v-model.trim="search"></el-input> -->
                            </div>
                        </template>
                        <template #default="d">
                            <el-link type="primary" :underline="false" v-on:click="open(d.row.eoMid)">
                                {{d.row.eoBrand}} /
                                {{d.row.eoModel}}
                            </el-link>
                        </template>
                    </vxe-column>
                    <vxe-column field="user" title="适用车型" min-width="280" align="center">
                        <template #default="d">
                            <span v-for="it in d.row.eoApplications.split('、')" :key="it" style="margin: 0 5px;">
                                <el-tag type="warning">{{it}}</el-tag>
                            </span>
                        </template>
                    </vxe-column>
                    <vxe-column field="eoPrice" title="售价(元)" width="150" align="center">
                        <template #default="d">
                            <span>{{d.row.biPrice}}</span>
</template>
                    </vxe-column>
                    <vxe-column field="eoPrice" title="支付方式" width="150" align="center">
                        <template #default="d">
                            <el-tag :type="d.row.payType == 1 ? '': d.row.payType == 2 ? 'success':'info'">{{d.row.payType==0?"现金": d.row.payType == 1 ? "微信": d.row.payType == 2 ? "支付宝":""}}</el-tag>
                        </template>
                    </vxe-column>
                    <vxe-column field="eoOldProce" title="底价(元)" min-width="180" align="center">
                        <template #default="d">
                            <span>{{d.row.eoOldProce||'无'}}</span>
</template>
                    </vxe-column>
                    <vxe-column field="eoStock" title="销售数量" min-width="180" align="center">
                        <template #default="d">
                            <span>{{d.row.biCount}}</span>
</template>
                    </vxe-column>
                    <vxe-column title="总利润(元)" min-width="180" align="center">
                        <template #default="d">
                            <el-link :type="d.row.biProfit>0?'primary':'danger'" :underline="false">{{d.row.biProfit}}</el-link>
                        </template>
                    </vxe-column>
                    <vxe-column field="eoAddTime" title="入库时间" min-width="180" align="center">
                        <template #default="d">
                            <span>{{d.row.addTime||'无'}}</span>
</template>
                    </vxe-column>
                    <vxe-column title="备注" min-width="250" align="center" show-overflow-tooltip>
                        <template #default="d">
                            <span>{{d.row.biMark}}</span>
</template>
                    </vxe-column>
                    <vxe-column title="操作" width="120" align="center" fixed="right">
                        <template #default="scope">
                            <el-button type="text" size="small"
                                       :disabled="scope.row.biStatus!=0||scope.row.openId!=optor.openId"
                                       v-on:click="add(1,scope.row.biId)">退换</el-button>
                            <el-button v-on:click="deleteRow(scope.$index,scope.row)"
                                       :disabled="!optor.root&&scope.row.openId!=optor.openId" type="text" size="small">
                                删除
                            </el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
            <el-drawer custom-class="el-drawer-fix" size="600px" v-if="dialog" :visible.sync="dialog"
                       :destroy-on-close="true" :close-on-press-escape="false" :wrapper-closable="false">
                <div slot="title">
                    {{form.optType==0?'新增':form.optType==1?'修改':''}}账单{{form.optType==3?'详情':''}}
                </div>
                <div v-if="dialog" class="flex-column hidden" style="position:absolute;top:0;bottom:0;left:0;right:0;">
                    <div class="flex-column-fill margin-8 hidden-x" style="padding-right:20px;">
                        <el-form size="medium" :model="form" ref="form" :rules="rules" label-position="top">

                            <el-form-item prop="mId" >
                                <template slot="label">
                                    机油品牌/型号
                                    <span v-if="!!form.eoId">（原订单：{{form.eoBrand}}【{{form.eoModel}}】） </span>
                                </template>
                                <el-cascader ref="cascader" v-model="form.mId" :options="eoModelList" clearable
                                             v-on:change="cascaderChange" :props="{emitPath:false,disabled:'disabled'}"
                                             v-on:visible-change="visibleChange(3)" style="width: 100%;"></el-cascader>
                            </el-form-item>
                            <el-form-item label="售出时间" prop="currentDay" >
                                <el-date-picker :disabled="form.optType>0" style="width: 100%;" v-model="form.currentDay"
                                                format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                                                :picker-options="pickerOptions">
                                </el-date-picker>

                            </el-form-item>

                            <el-form-item label="售价/元" prop="biPrice" >
                                <template slot="label">
                                    售价/元
                                    <span v-if="!!currentEo">（正常售价：￥{{currentEo.eoPrice}}）</span>
                                </template>
                                <el-input-number :disabled="form.optType>0" v-model="form.biPrice" :precision="2"
                                                 :step="0.1" label="请输入售价">
                                </el-input-number>
                            </el-form-item>
                            <el-form-item label="售出数量" prop="count" >
                                <template slot="label">
                                    售出数量
                                    <span v-if="!!currentEo"
                                          :style="{'color':currentEo.eoStock<=0?'red':''}">（{{currentEo.eoStock<=0?'库存不足无法出售，请及时补货':'库存：'+currentEo.eoStock}}）</span>
                                </template>
                                <el-input-number :disabled="form.optType>0" v-model="form.count" label="请输入售出数量"
                                                 :precision="0">
                                </el-input-number>
                            </el-form-item>
                            <el-form-item label="支付方式" prop="payType"  v-removeAriaHidden>
                                <el-radio-group :disabled="form.optType>0" v-model="form.payType">
                                    <el-radio :label="0">现金支付</el-radio>
                                    <el-radio :label="1">微信支付</el-radio>
                                    <el-radio :label="2">支付宝支付</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="备注" prop="biMark">
                                <el-input type="textarea" placeholder="请输入备注" v-model="form.biMark" maxlength="400"
                                          show-word-limit>
                                </el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="padding-10 border-top-solid border-greyLight">
                        <el-button-group>
                            <el-button type="info" plain v-on:click="dialog=false" icon="fa fa-rotate-left" size="small">
                                取消
                            </el-button>
                            <el-button type="primary" icon="fa fa-check" v-on:click="submit" size="small">确 定</el-button>
                        </el-button-group>
                    </div>
                </div>
            </el-drawer>
        </div>
</template>
<script>
    module = (function (hxt) {
        return {
            name: 'bill',
            props: {

            },
            data: function () {
                var _this = this, optor = hxt.store.optor;
                return {
                    optor: optor,
                    tableData: [],
                    date: null,
                    query: {
                        eoApplications: '',
                        bId: '',
                        beginTime: '',
                        endTime: '',
                        pageIndex: 1,
                        pageSize: 20,
                        rowCount: 0,
                        Sum: 0,
                        Count: 0,
                        Profit: 0,
                        XJ: 0,
                        WX: 0,
                        ZFB: 0,
                    },
                    dialog: false,
                    currentEo: null,
                    form: {
                        optType: 0,
                        mId: 0,
                        payType: 0,
                        biPrice: '',
                        count: 1,
                        biMark: '',
                        currentDay: '',
                        openId: '',
                        state: 'bill'
                    },
                    oldform: '',
                    eoModelList: [],
                    carList: [],
                    defaultValue: '',
                    pickerOptions: {
                        disabledDate: function (time) {
                            return time.getTime() > Date.now();
                        },
                        shortcuts: [{
                            text: '最近一周',
                            onClick: function (picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                            text: '最近一个月',
                            onClick: function (picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                            text: '最近三个月',
                            onClick: function (picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                            text: '最近半年',
                            onClick: function (picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * (365 / 2));
                                picker.$emit('pick', [start, end]);
                            }
                        }]
                    },
                    rules: {
                        mId: [{
                            required: true,
                            message: '请选择机油品牌/型号'
                        }, {
                            validator: function (rule, value, callback) {
                                if (value <= 0) return callback(new Error('请选择机油品牌/型号'));
                                callback();
                            }
                        }],
                        currentDay: [{
                            required: true,
                            message: '请选择售出时间'
                        }],
                        biPrice: [{
                            required: true,
                            message: '请输入售价'
                        }, {
                            validator: function (rule, value, callback) {
                                if (value <= 0) return callback(new Error('请输入售价'));
                                callback();
                            }
                        }],
                        count: [{
                            required: true,
                            message: '请输入售出数量'
                        }, {
                            validator: function (rule, value, callback) {
                                if (value <= 0) return callback(new Error('请输入售出数量'));
                                callback();
                            }
                        }]
                    },
                }
            },
            computed: {

            },
            watch: {

            },
            activated: function () {
            },
            mounted: function () {
                var _this = this;
                _this.defaultValue = hxt.dateFormat('yyyy-MM-01');
                _this.loadList();
            },
            methods: {
                loadList: function () {
                    var _this = this;
                    _this.tableData = [];
                    _this.query.openId = _this.optor.openId;
                    _this.query.beginTime = _this.date ? _this.date[0] : '';
                    _this.query.endTime = _this.date ? _this.date[1] : '';
                    hxt.post({
                        url: hxt.config.link +'pc/enBillList',
                        data: _this.query,
                        ok: function (res) {
                            if (res.code != 0) return hxt.error('加载列表失败：' + res.errmsg);
                            var list = res.data.list;
                            _this.query.rowCount = res.data.rowCount;
                            _this.query.pageIndex = res.data.pageIndex;
                            _this.query.pageSize = res.data.pageSize;
                            _this.query.Sum = res.data.Sum;
                            _this.query.Count = res.data.Count;
                            _this.query.Profit = res.data.Profit;
                            _this.query.XJ = res.data.XJ;
                            _this.query.WX = res.data.WX;
                            _this.query.ZFB = res.data.ZFB;
                            _this.tableData = list;
                        }
                    });
                },
                open: function (eoMid) {
                    this.$router.push({ path: '/201?bId=' + eoMid });
                },
                pagerSizeChange: function (val) {
                    var _this = this;
                    _this.query.pageSize = val;
                    if (Math.ceil(_this.query.rowCount * 1.0000 / val) >= _this.query.pageIndex) _this.loadList();
                },
                pagerIndexChange: function (val) {
                    var _this = this;
                    _this.query.pageIndex = val;
                    _this.loadList();
                },
                visibleChange: function (type) {
                    var _this = this;
                    if (type == 1) {
                        hxt.post({
                            url: hxt.config.link +'pc/eoModelList',
                            data: {},
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('加载列表失败：' + res.errmsg);
                                _this.eoModelList = res.data;
                            }
                        });
                        return;
                    };
                    if (type == 2) {
                        hxt.post({
                            url: hxt.config.link +'pc/getCars',
                            data: {},
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('加载列表失败：' + res.errmsg);
                                _this.carList = res.data;
                            }
                        });
                        return;
                    };
                    if (type == 3) {
                        hxt.post({
                            url: hxt.config.link +'pc/eoModelList',
                            data: {},
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('加载列表失败：' + res.errmsg);
                                _this.eoModelList = res.data.map(function (item) {
                                    return {
                                        label: item.text,
                                        value: item.value,
                                        children: item.children.map(function (it) {
                                            return {
                                                value: it.value,
                                                label: it.text,
                                                disable: it.disable,
                                                eoStock: it.eoStock,
                                                eoPrice: it.eoPrice,
                                                eoBrand: it.eoBrand
                                            }
                                        })
                                    }
                                });;
                            }
                        });
                    };

                },
                footerMethod: function (d) {
                    var _this = this;
                    const sums = [];
                    d.columns.forEach(function (item, index) {
                        if (index === 0) {
                            sums[index] = '合计';
                            return;
                        };
                        if (index === 1) {
                            sums[index] = '销售额：' + _this.query.Sum + '元';
                            return;
                        };
                        if (index === 2) {
                            sums[index] = '现金：' + _this.query.XJ + '元';
                            return;
                        };
                        if (index === 3) {
                            sums[index] = '微信：' + _this.query.WX + '元';
                            return;
                        };
                        if (index === 4) {
                            sums[index] = '支付宝：' + _this.query.ZFB + '元';
                            return;
                        };
                        if (index === 5) {
                            sums[index] = '总利润：' + _this.query.Profit + '元';
                            return;
                        };
                    });
                    // 返回一个二维数组的表尾合计
                    return [sums];
                },
                getSummaries: function (d) {
                    var _this = this;
                    const sums = [];
                    
                    d.columns.forEach(function (item, index) {
                        if (index === 0) {
                            sums[index] = '合计';
                            return;
                        };
                        if (index === 1) {
                            sums[index] = '销售额：' + _this.query.Sum + '元';
                            return;
                        };
                        if (index === 2) {
                            sums[index] = '现金：' + _this.query.XJ + '元';
                            return;
                        };
                        if (index === 3) {
                            sums[index] = '微信：' + _this.query.WX + '元';
                            return;
                        };
                        if (index === 4) {
                            sums[index] = '支付宝：' + _this.query.ZFB + '元';
                            return;
                        };
                        if (index === 5) {
                            sums[index] = '总利润：' + _this.query.Profit + '元';
                            return;
                        };
                    });
                    return sums;
                },
                goEO: function (eoBrand, eoModel) {
                    //this.$router.push("engineOil");
                },
                cascaderChange: function (e) {
                    var _this = this,
                        nodesInfo = this.$refs.cascader.getCheckedNodes();
                    if (nodesInfo.length <= 0) return _this.$message.error("无效的选项");
                    _this.currentEo = nodesInfo[0].data;
                    if (_this.currentEo.eoBrand != _this.form.eoBrand || _this.currentEo.label != _this.form.eoModel) {
                        if (_this.form.optType == 1) _this.form.biMark = _this.form.bioldMark + '  原订单：' + _this.form
                            .eoBrand + '【' + _this.form.eoModel + '】更换为' + _this.currentEo.eoBrand + '【' + _this.currentEo
                                .label + '】';
                        return;
                    };
                    if (_this.form.optType == 1) _this.form.biMark = _this.form.bioldMark;
                },
                deleteRow: function (index, row) {
                    var _this = this,
                        openId = _this.optor.openId;
                    hxt.confirm('注意：删除后不能找回, 是否继续?', '提示', function () {
                        hxt.post({
                            url: hxt.config.link +'pc/eoBillAdd',
                            data: {
                                optType: 2,
                                biId: biId,
                                openId: openId,
                                state: 'bill'
                            },
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('删除失败：' + res.errmsg);
                                hxt.success('删除成功');
                                _this.tableData.splice(index, 1);
                            }
                        });
                    });
                },
                add: function (type, biId) {
                    var _this = this;
                    if (type > 0) {
                        _this.visibleChange(3);
                        hxt.post({
                            url: hxt.config.link +'pc/eoBillAdd',
                            data: {
                                biId: biId
                            },
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('获取账单详情失败：' + res.errmsg);
                                var g = res.data;
                                if (type == 3) {
                                    _this.form = g;
                                };
                                _this.form.optType = type;
                                _this.form.biPrice = g.biPrice;
                                _this.form.count = g.biCount;
                                _this.form.biMark = g.biMark;
                                _this.form.bioldMark = g.biMark;
                                _this.form.currentDay = g.time;
                                _this.form.eoBrand = g.eoBrand;
                                _this.form.eoModel = g.eoModel;
                                _this.form.eoId = g.eoId;
                                _this.form.payType = g.payType;
                                _this.form.biId = g.biId;
                                _this.form.mId = String(g.eoMid),
                                    _this.oldform = JSON.stringify(_this.form);
                                _this.dialog = true;
                            }
                        });
                    } else {
                        _this.form.optType = 0;
                        _this.form.biPrice = 0;
                        _this.form.count = 0;
                        _this.form.biMark = "";
                        _this.form.bioldMark = "";
                        _this.form.currentDay = "";
                        _this.form.eoBrand = "";
                        _this.form.eoModel = "";
                        _this.form.eoId = 0;
                        _this.form.payType = 0;
                        _this.form.biId = 0;
                        _this.form.mId = String(0),
                            _this.oldform = "";
                        _this.dialog = true;
                    };
                    
                },
                submit: function () {
                    var _this = this;
                    if (!!_this.oldform && (JSON.parse(_this.oldform).mId == _this.form.mId)) return hxt.error("提交失败：信息未更改");
                    if (!!_this.currentEo && (_this.form.mId == _this.currentEo.mId)) return hxt.error("提交失败：品牌型号与原订单相同");
                    hxt.validateElForm(_this, "form", function () {
                        hxt.post({
                            url: hxt.config.link +'pc/eoBillAdd',
                            data: _this.form,
                            ok: function (res) {
                                if (res.code != 0) return hxt.error('提交失败：' + res.errmsg);
                                hxt.success('提交成功');
                                _this.loadList();
                                _this.dialog = false;
                            }
                        });
                    });
                },
                exportEcel: function (e) {
                    var _this = this;
                    var url = hxt.config.link + "pc/billListExport";
                    url += '?pageIndex=' + _this.query.pageIndex;
                    url += '&pageSize=' + _this.query.rowCount;
                    url += '&eoApplications=' + _this.query.eoApplications;
                    url += '&bId=' + _this.query.bId;
                    url += '&beginTime=' + _this.query.beginTime;
                    url += '&endTime=' + _this.query.endTime;
                    window.open(url);
                }
            },
            components: {
            }
        };
    })(window.$jscript.fn);
</script>
<style>
    .el-tab-pane {
        height: 100%;
    }

    .el-tabs__content {
        flex: 1;
    }

    .el-tabs--border-card > .el-tabs__content {
        padding: 0px !important;
    }
</style>